<template>
<div class="data-bar">
    <div ref="chart" style="width: 100%; height: 500px; margin: 50px 0 0 50px;"></div>
</div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import * as echarts from 'echarts';
import { getDataset } from '../../api/datasetApi.ts';

export default {
  // 启动函数
  setup(){
    const state = reactive({
      chart:ref()
    })

    var data = ref([])

    const init = () => {
      if(state.chart){
        let mycat = echarts.init(state.chart)
        const option = {
          title: {
            text: '功能使用次数',
            x: 'center',
            textStyle: {
              color: '#9c0505'
            }
          },
          tooltip: {},
          xAxis: {
            type: 'category',
            data: data.value.map(item => item.action),
            axisLabel: {
              rotate: 30,
              interval: 0
            }
          },
          yAxis: {
            type: 'value',
            min: 0, // 设置纵坐标最小值
            max: Math.max(...data.value.map(item => item.count)) + 10 // 动态计算最大值并留出一些空间
          },
          series: [{
            type: 'bar',
            data: data.value.map(item => item.count)
          }]
        };
        mycat.setOption(option);
        }
    }

    const initChart = async () => {
      try {
        const res = await getDataset(); 
        console.log(res);
        data.value = res; 
        
        init() 
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    };

    onMounted(() => {
      initChart();
    })

    return state
  }
}
</script>
